const router = require('koa-router')()
const Role = require('../modules/RoleSchema')
const util = require('../utils/util.js')
router.prefix('/roles')
// 登錄
router.get('/allList', async (ctx) => {
  try {
    const list = await Role.find({}, '_id roleName')
    ctx.body = util.success(list)
  } catch (error) {
    util.fail(`异常错误${error.stack}`)
  }
})
// 列表
router.get('/list', async (ctx) => {
  const { roleName } = ctx.request.query
  const { page, skipIndex } = util.pager(ctx.request.query)
  try {
    let params = {}
    if (roleName) params.roleName = roleName
    const query = Role.find(params)
    const list = await query.skip(skipIndex).limit(page.pageSize)
    const total = await Role.countDocuments(params)
    ctx.body = util.success({
      list,
      page: {
        ...page,
        total,
      },
    })
  } catch (error) {
    ctx.body = util.fail(`查询失败:${error.stack}`)
  }
})
//增删改
router.post('/operate', async (ctx) => {
  const { _id, action, roleName, remark } = ctx.request.body
  let info, res
  try {
    if (action == 'add') {
      res = await Role.create({ roleName, remark })
      info = '创建成功'
    } else if (action == 'edit') {
      if (_id) {
        let params = { roleName, remark }
        res = await Role.findByIdAndUpdate(_id, params)
        info = '编辑成功'
      } else {
        ctx.body = util.fail('缺少必要参数:_id')
      }
    } else {
      if (_id) {
        res = await Role.findByIdAndRemove(_id)
        info = '删除成功'
      } else {
        ctx.body = util.fail('缺少必要参数:_id')
      }
    }
    ctx.body = util.success(res, info)
  } catch (error) {
    ctx.body = util.fail(error.stack)
  }
})
router.post('/update/persion', async (ctx) => {
  const { _id, permissionList } = ctx.request.body
  try {
    if (_id) {
      let res = await Role.findByIdAndUpdate(_id, { permissionList })
      ctx.body = util.success(res, '设置成功')
    } else {
      ctx.body = util.fail('缺少必要参数:_id')
    }
  } catch (error) {
    ctx.body = util.fail(error.stack)
  }
})

module.exports = router
